package com.tsing.tsingfengmall.file.config;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.RemovalCause;
import com.github.benmanes.caffeine.cache.Scheduler;
import com.tsing.tsingfengmall.file.dto.TaskInfoDTO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Caffeine配置类
 *
 * @author TheTsing
 */
@Configuration
public class CacheConfig {

    @Value("${minio.bucket}")
    private String bucket;

    private final AsyncMinioClient asyncMinioClient;

    public CacheConfig(AsyncMinioClient asyncMinioClient) {
        this.asyncMinioClient = asyncMinioClient;
    }

    @Bean
    public Cache<String, TaskInfoDTO> taskCache() {
        return Caffeine.newBuilder()
                .expireAfterWrite(2, TimeUnit.HOURS)
                .scheduler(Scheduler.forScheduledExecutorService(Executors.newScheduledThreadPool(2)))
                .removalListener((String uploadId, TaskInfoDTO taskInfoDTO, RemovalCause cause) -> {
                    try {
                        asyncMinioClient.abortMultipartUploadAsync(bucket, null, taskInfoDTO.getObjectName(), uploadId, null, null).get();
                    } catch (Exception e) {
                    }
                })
                .build();
    }

}
